package com.cloud.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cloud.commonapi.jsonResult.Result;
import com.cloud.commonapi.model.Goods_info;
import com.cloud.commonapi.model.User_info;
import com.cloud.transaction.service.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author 陈楚城
 * @date 2019/9/29 14:44
 */
@RestController
@Api(tags = "物品交易模块接口")
@RequestMapping("/transaction/goods")
public class goodscontroller {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("")
    @ApiOperation(value = "发布闲置物品" ,notes="未测试")
    public Result add(Goods_info goods_info, @RequestParam(value = "file", required = false) MultipartFile file, HttpSession session){

        //查看用户的信誉积分
        JSONObject jSONObject= restTemplate.getForObject("http://usercenter/usercontroller/userinfo/users/"+(Integer) session.getAttribute("loginId"),JSONObject.class);
        JSONObject  data=jSONObject.getJSONObject("data");
        User_info user_info=JSON.parseObject(data.toString(), User_info.class);
        System.out.println(user_info.getUsername());
        if(user_info.getCredit()<60){
            return Result.build(400,"您的信誉不合格，请快去实名吧！");
        }
        if(file!=null) {
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "G:\\web\\html\\img\\"; // 上传后的路径
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            goods_info.setPricture("http://10.86.2.41:8090/img/" + fileName);
        }
        goods_info.setAccountId((Integer) session.getAttribute("loginId"));//获取登录账号id
        goods_info.setStatus(1);//物品状态
        goods_info.setTime(new Timestamp(new Date().getTime()));//发布时间
        if(goodsService.add(goods_info) >0)
            return Result.build(200,"发布成功");
        else
            return Result.build(400,"发布失败");
    }
    @GetMapping("/list")
    @ApiOperation(value = "查看物品列表",notes = "未测试")
    public Result selectgoodslist(HttpSession session){
        List<Goods_info> list = goodsService.selectgoodslist();
        System.out.println(session.getId());
        if(list.size()>0){
            return Result.buildData(202,"查询成功",list);
        }
        return Result.build(400,"查询失败");

    }
    @GetMapping("/{id}")
    @ApiOperation(value = "查看物品详情",notes = "未测试")
    public Result selectgoodsbyId(@PathVariable Integer id,HttpSession session){
        Goods_info goods_info = goodsService.selectgoodsbyId(id);
        JSONObject jSONObject= restTemplate.getForObject("http://usercenter/usercontroller/userinfo/users/"+goods_info.getAccountId(),JSONObject.class);
        JSONObject  data=jSONObject.getJSONObject("data");
        User_info user_info=JSON.parseObject(data.toString(), User_info.class);
        System.out.println(user_info.getUsername());
        HashMap<String,Object> map=new HashMap<>();
        map.put("goods_info" ,goods_info);
        map.put("username",user_info.getUsername());
        map.put("accountId",user_info.getAccountId());
        map.put("level",user_info.getLevel());
        if(map.size()>0){
            return Result.buildData(202,"查询成功",map);
        }
        return Result.build(400,"查询失败");


    }

    @GetMapping("/ByOredr/{id}")
    @ApiOperation(value = "查看物品详情",notes = "未测试")
    public Result selectgoodsbyId1(@PathVariable Integer id,HttpSession session){
        Goods_info goods_info = goodsService.selectgoodsbyId(id);
        if(goods_info!=null){
            return Result.buildData(202,"查询成功",goods_info);
        }
        return Result.build(400,"查询失败");


    }

    @PostMapping("/keyword")
    @ApiOperation(value = "关键字搜索物品",notes = "未测试")
    public Result selectgoodsbykeyword(@RequestParam(value = "keyword",required = false) String keyword,HttpSession session){
        if(keyword==null){
            keyword="";
        }
        List<Goods_info> list = goodsService.selectgoodsbykeyword(keyword);
        if(list.size() > 0){
            return Result.buildData(202,"查询成功",list);
        }
        return Result.build(400,"查询失败");

    }
    @PutMapping("update")
    @ApiOperation(value = "修改闲置物品" ,notes="未测试")
    public Result update(Goods_info goods_info, @RequestParam(value = "file", required = false) MultipartFile file, HttpSession session){
        if(file!=null) {
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "G:\\web\\html\\img\\"; // 上传后的路径
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            goods_info.setPricture("http://10.86.2.41:8090/img/" + fileName);
        }
        if(goodsService.updategoods(goods_info) >0)
            return Result.build(200,"修改成功");
        else
            return Result.build(400,"修改失败");
    }
    @PutMapping("")
    @ApiOperation(value = "修改物品信息",notes = "未测试")
    public Result updategoods( Goods_info goods_info,HttpSession session){
        if(goodsService.updategoods(goods_info) > 0){
            return Result.build(200,"修改成功");

        }
        return Result.build(400,"修改失败");
    }
    @PutMapping("Byorder")
    @ApiOperation(value = "修改物品信息",notes = "未测试")
    public Result updategoods1(@RequestBody Goods_info goods_info,HttpSession session){
        if(goodsService.updategoods(goods_info) > 0){
            return Result.build(200,"修改成功");

        }
        return Result.build(400,"修改失败");
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "下架物品",notes = "未测试")
    public Result deletegoods(@PathVariable Integer id,HttpSession session){
        if(goodsService.deletegoods(id) > 0){
            return  Result.build(200,"下架成功");

        }
        return Result.build(400,"下架失败");
    }
    @GetMapping("/accountId/list")
    @ApiOperation(value = "查看个人发布的物品",notes = "未测试")
    public Result selectlistbyaccountId(HttpSession session){
        Integer account = (Integer) session.getAttribute("loginId");//session中获取
        JSONObject jSONObject= restTemplate.getForObject("http://usercenter/usercontroller/userinfo/users/"+account,JSONObject.class);
        JSONObject  data=jSONObject.getJSONObject("data");
        User_info user_info=JSON.parseObject(data.toString(), User_info.class);
        List<Goods_info> list =goodsService.listbyaccountId(account);
        HashMap<String,Object> map=new HashMap<>();
        map.put("list",list);
        map.put("user_info",user_info);
        if(map.size() >0)
            return Result.buildData(202,"查询成功",map);
        return Result.build(400,"查询失败");
    }

    @GetMapping("/accountIdByorder/list/{account}")
    @ApiOperation(value = "查看个人发布的物品",notes = "未测试")
    public Result selectlistbyaccountId1(@PathVariable Integer account,HttpSession session){

        List<Goods_info> list =goodsService.listbyorder(account);
        if(list.size() >0)
            return Result.buildData(202,"查询成功",list);
        return Result.build(400,"查询失败");
    }

    @GetMapping("/pagelist/{page}/{pagesize}")
    @ApiOperation(value = "分页",notes = "未测试")
    public Result selectgoodslistbyPage(@PathVariable int page,@PathVariable int pagesize, HttpSession session){
        IPage<Goods_info> pagelist = goodsService.selectPage(page,pagesize);
        List<Goods_info> list=pagelist.getRecords();
       if(list.size()>0){
          return Result.buildData(202,"查询成功",list);
       }
          return Result.build(400,"查询失败");
    }
}
